package com.yntsoft.controller;

import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yntsoft.entity.ShiroUser;
import com.yntsoft.exception.CustomException;
import com.yntsoft.util.EhcacheUtil;

/**
 * 登陆控制层
 * @author Tony
 *
 */
@Controller
public class LoginController {

	/**
	 * 登陆控制层
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "login")
	public String login(HttpServletRequest request)throws Exception{
		//如果登陆失败从request中获取认证异常信息，shiroLoginFailure就是shiro异常类的全限定名
		String  exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
		if(exceptionClassName!=null){
			if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
				//最终会抛给异常处理器
				throw new CustomException("账号不存在");
			} else if (IncorrectCredentialsException.class.getName().equals(
					exceptionClassName)) {
				String userName = request.getParameter("username");
				AtomicInteger atomicInteger = (AtomicInteger) EhcacheUtil.getInstance().get(userName, "retryCount");
				throw new CustomException("用户名/密码错误" + "已输尝试：" + atomicInteger.get() + "次，尝试5次后账号锁2小时");
			} else if("randomCodeError".equals(exceptionClassName)){
				throw new CustomException("验证码错误 ");
			}if (ExcessiveAttemptsException.class.getName().endsWith(exceptionClassName)) {
				// diskExpiryThreadIntervalSeconds 磁盘失效线程运行时间间隔，默认是120秒。所以 这里 的时间间隔  为 2分钟 
				throw new CustomException("密码输入次数超过五次，请2小时后再试");
			} else {
				throw new Exception();//最终在异常处理器生成未知错误
			}
		}
		return "login";
	}
	
	/**
	 * 打开登陆页面
	 * @return 
	 */
	@RequestMapping(value = "toLogin")
	public String toLogin(HttpSession session){
		return "login";
	}
	
	
	
	
	
	/**
	 * 打开登陆页面
	 * @return 
	 */
	@RequestMapping(value = "logout")
	public String logout(HttpSession session){
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
		}
		return "login";
	}
}
